package copyHelperV2;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;

public class CopyDir {

	private static BufferedInputStream in = null;
	private static BufferedOutputStream out = null;

	public static void copyDir(File quelle, File ziel, boolean uberschreiben)
			throws FileNotFoundException, IOException {

		File[] files = quelle.listFiles();
		ziel.mkdirs();
		for (File file : files) {
			if (file.isDirectory()) {
				copyDir(file,
						new File(ziel.getAbsolutePath()
								+ System.getProperty("file.separator")
								+ file.getName()), uberschreiben);
			} else {
				copyFile(file,
						new File(ziel.getAbsolutePath()
								+ System.getProperty("file.separator")
								+ file.getName()), uberschreiben);
			}
		}
	}

	public static void copyFile(File file, File ziel, boolean uberschreiben)
			throws IOException {
		
		NewJFrame.setLoadLabel(file);
		
		
//		try {
//			Thread.sleep(300);
//		} catch (InterruptedException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
//		
		
		
		if (ziel.exists() && uberschreiben || !ziel.exists()) {
			for (File element : ziel.getParentFile().listFiles()) {
				boolean gleich = true;
				BufferedReader br1 = new BufferedReader(new FileReader(file));
				BufferedReader br2 = new BufferedReader(new FileReader(element));
				for (int i = 0; i < 25000 && gleich; i++) {
					gleich = br1.read() == br2.read();
				}
				if (gleich)
					return;
			}
			ziel.delete();

			in = new BufferedInputStream(new FileInputStream(file));
			out = new BufferedOutputStream(new FileOutputStream(ziel, true));
			int bytes = 0;
			System.out.println("es wird kopiert: \""+file.getPath()+"\"");

			while ((bytes = in.read()) != -1) {
				out.write(bytes);
			}

			in.close();
			out.close();
		}

	}
}
